// pages/index/index.js
import {Cache} from "../../utils/cache.js"
import {URL, VERSION,TENCENT_API} from "../../config/api.js"


import tools from "../../utils/tools.js"

const cache = new Cache()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cateList:null,
    cate_id:0,
    list:[],
    page:1,
    total_page:0,
    isButtom:true,
    isAuth:false,
    location:"定位中...",
    lat:0,
    lon:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let token = cache.getCache('token')
    // 获取分类信息
      this.getCate(token)
      // 获取地理位置
      this.getLocation()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  /**
   * 
   * 获取选项卡内容
   * @param {*} token 
   */
  getCate(token){
    wx.request({
      url: URL + VERSION +'cateList',
      header:{AUTHORIZATION:token},
      success:res=>{
          if(res.data.code == 200) {
            var cate_id = res.data.data[0]['id']
              this.setData({
                cateList:res.data.data,
                cate_id:cate_id
              })
              this.getList(token,cate_id)
          } else {
            wx.showToast({
              title: '获取失败',
            })
          }
      }
    })
  },
  getList(token,cate_id){

    wx.request({
      url: URL + VERSION +'list',
      data:{cate_id:cate_id},
      header:{AUTHORIZATION:token},
      success:res=>{
          if(res.data.code == 200) {
             this.setData({
               list:res.data.data.data,
               page:1,
               total_page:res.data.data.last_page
             })
          } else {
            wx.showToast({
              title: '获取失败',
            })
          }
      }
    })
  },
  // 切换更新数据
  changeTabs:function(event){
    let cate_id =event.detail.activeKey
    let token = cache.getCache('token')
    this.getList(token,cate_id)
  },
  // 触底加载
  onReachBottom:function(event){
    let that = this
    let next_page = that.data.page + 1 // 当前页 + 1 = 下一页
    let token = cache.getCache('token')
    if(next_page > that.data.total_page) {
      wx.showToast({
        title: '已经加载完毕',
      })

      that.setData({
        isButtom:false
      })
      return 
    }
    wx.request({
      url: URL + VERSION +'list',
      data:{cate_id:that.data.cate_id,page:next_page},
      header:{AUTHORIZATION:token},
      success:res=>{
          if(res.data.code == 200) {
             this.setData({
               list:that.data.list.concat(res.data.data.data),// 刚加载的数据、追加到原来的数据里面
               page:next_page,
               total_page:res.data.data.last_page
             })
          } else {
            wx.showToast({
              title: '获取失败',
            })
          }
      }
    })
    

  },

  //下拉刷新
  onPullDownRefresh:function(event){
    let token = cache.getCache('token')
    let cate_id = this.data.cate_id
    this.getList(token,cate_id)
  },
  // 喜欢
  like:tools.debounce(function(event){
    console.log(event)
    let id = event[0].currentTarget.dataset.id
    let token = cache.getCache('token')
    let index =  event[0].currentTarget.dataset.index
    // 没有授权的用户、先弹出授权、更新昵称头像
    if(!event[0].currentTarget.dataset.isauth) {
      wx.getUserProfile({
        desc: '获取用户昵称、头像',
        success:res=>{
          console.log(res)
          wx.request({
            url: URL + VERSION +'updateAuthMessage',
            data:{nickname:res.userInfo.nickName,avatar:res.userInfo.avatarUrl},
            header:{AUTHORIZATION:token},
            method:"POST",
            success:res=>{
              this.setData({
                isAuth:true
              })
            }
          })
        }
      })
    }
  
    wx.request({
      url: URL + VERSION +'like',
      data:{article_id:id},
      header:{AUTHORIZATION:token},
      success:res=>{
          if(res.data.code == 200) {
            let list = this.data.list
            if(res.data.data.type == 1) {
                // 取消点赞
                list[index]['is_like'] = false
                list[index]['like_count'] = list[index]['like_count'] - 1
            } else {
                // 点赞
                list[index]['is_like'] = true
                list[index]['like_count'] = list[index]['like_count'] + 1
            }
            this.setData({
              list
            })

          } else {
            wx.showToast({
              title: '操作失败',
            })
          }
      }
    })
  }),
  /**
   * 定位
   */
  getLocation:function(){
    wx.showLoading({
      "title":"正在定位中..."
    })
    let token = cache.getCache('token')
    wx.getLocation({
      altitude: 'altitude',
      success:res=>{
        let lat = res.latitude
        let lon = res.longitude
        wx.request({
          url:TENCENT_API.geocoder + 'key=' + TENCENT_API.key+ '&location=' + lat + ',' + lon,
          success:res=>{
            if(res.data.status == 0) {
              let city = res.data.result.address_component.city
              this.setData({
                location:city,
                lat:lat,
                lon:lon
              })
              wx.request({
                url: URL + VERSION +'updateLocationMessage',
                header:{AUTHORIZATION:token},
                data:{city:city,lat:lat,log:lon},
                method:"POST",
                success:res=>{
                  wx.hideLoading({
                    success: (res) => {},
                  })
                  console.log(res)
                }
              })
            }
          }
        })
      }
    })
  }

})